import { systemTime as systemNow } from "./api/api.js"
// import VueCookies from "vue-cookies"
import Jsonp from "@/request/jsonp"

// 获取版本
let getVerson = (ua, type) => {
  if (type > 0) {
    return 0
  } else {
    return ua.substring(ua.indexOf(type) + type.length, ua.length).split("_")[3]
  }
}
// 获取主域名
export const uleUrl = () => {
  return import.meta.env.VITE_APP_HOST
}
// 获取cdn域名
export const uleCdn = () => {
  return import.meta.env.VITE_APP_HOST_CDN
}
// 获取当前client
export const browser = () => {
  let ua = navigator.userAgent.toLowerCase()
  let uappType = {
    ule: false,
    ylxd: false,
    ylxdsq: false,
    yzg: false,
    yzgxd: false,
    wx: ua.match(/micromessenger/i),
    wxwork: ua.match(/wxwork/i),
    miniprogram: !!~ua.indexOf("miniprogram"),
    ios: ua.match(/(iphone|ipod|ipad);?/i),
    android: ua.match(/android/i),
    version: 0
  }
  if (~ua.indexOf("uleapp/")) {
    // 邮乐App
    uappType.version = getVerson(ua, "uleapp/")
    uappType.ule = true
  }
  // 邮乐小店 App
  if (~ua.indexOf("ulxdapp/") && !~ua.indexOf("ylxdsq")) {
    uappType.version = getVerson(ua, "ulxdapp/")
    uappType.ylxd = true
  }
  // 邮乐优鲜APP
  if (~ua.indexOf("ylxdsq")) {
    uappType.version = getVerson(ua, "ulxdapp/")
    uappType.ylxdsq = true
  }
  // 邮掌柜APP
  if (~ua.indexOf("uzgapp/")) {
    uappType.version = getVerson(ua, "uzgapp/")
    uappType.yzg = true
  }
  // 邮掌柜小店APP
  if (~ua.indexOf("uzgxdapp/")) {
    uappType.version = getVerson(ua, "uzgxdapp/")
    uappType.yzgxd = true
  }
  return uappType
}
/**
 * 获取缓存数据
 * key 模块
 * val 模块对应值
 */
export const Local = {
  fetch(key) {
    let data = localStorage.getItem(key)
    return data ? JSON.parse(data) : null
  },
  save(key, items) {
    localStorage.setItem(key, JSON.stringify(items))
  }
}

// 获取地址上的参数
export const getParam = (str, name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  let r = str.split("?")[1]
  if (r) {
    let arr = ""
    arr = r.match(reg)
    return arr ? decodeURIComponent(arr[2]) : null
  } else {
    return null //返回参数值
  }
}

// 获取storeid
export const getStoreId = () => {
  let ylxdMall = Local.fetch("ylxdMall") || "",
    localStoreId = null,
    w = window.location.href,
    storeId = ""
  if (ylxdMall) {
    if ("user" in ylxdMall) {
      localStoreId = ylxdMall.user.useronlyid
    }
  }
  storeId = getParam(w, "storeid") || getParam(w, "store_id") || getParam(w, "storeId") || localStoreId
  console.log(storeId, "storeid")
  return storeId
}

// Description: 丢头处理
export const lostTitle = (title) => {
  if (window.dsBridge && typeof window.dsBridge === "object") {
    window.dsBridge.call("setNativeTitle", {
      title: title
    })
  }
}

// Description: APP内返回
export const uleBack = (back) => {
  if (browser().ylxd) {
    // let back = window.history.go(-1) // 当为undefined时候，说明已经到最上一层了, 此方式还未验证
    // if (back == undefined) {
    //   console.log('app返回')
    //   if (navigator.userAgent.indexOf("Android") > -1) {
    //     location.href = "ulemobile://ulePopView"; // APP首页跳转
    //   } else {
    //     // 兼容 ios 8
    //     location.href = "objc:ulemobile://ulePopView"; // APP 首页跳转
    //   }
    // }
    if (back && back == "true") {
      history.go(-1)
      return
    }
    if (window.history.length <= 1 || !document.referrer) {
      if (navigator.userAgent.indexOf("Android") > -1) {
        location.href = "ulemobile://ulePopView" // APP首页跳转
      } else {
        // 兼容 ios 8
        location.href = "objc:ulemobile://ulePopView" // APP 首页跳转
      }
    } else {
      history.go(-1)
    }
  } else if (browser().yzg) {
    if (window.history.length <= 1 || !document.referrer) {
      location.href = "ulemobile://ulePopView" // APP首页跳转
    } else {
      history.go(-1)
    }
  } else {
    history.go(-1)
  }
}

// share analysis: APP内返回
export const shareBack = () => {
  if (browser().ylxd) {
    if (navigator.userAgent.indexOf("Android") > -1) {
      location.href = "ulemobile://ulePopView" // APP首页跳转
    } else {
      // 兼容 ios 8
      location.href = "objc:ulemobile://ulePopView" // APP 首页跳转
    }
  } else {
    history.go(-1)
  }
}

// 服务器系统当前时间
let isLoad = true
let timeDiff = ""
export const systemTime = async () => {
  let datatime = ""
  if (isLoad) {
    let xhr = await systemNow()
    if (xhr.status == 200) {
      // 服务器返回的是秒，要转成毫秒
      datatime = Number(xhr.data) * 1000
    }
    timeDiff = new Date().getTime() - datatime
    isLoad = false
  }
  let time = new Date()
  if (timeDiff) {
    time = new Date(new Date().getTime() - timeDiff)
  }
  return time
}

/**
 * 倒计时
 * startTime 开始时间
 * endTime 结束时间
 * callback 返回函数
 */
export const getCountDown = (startTime, endTime, callback) => {
  let startSeconds
  let endSeconds
  let timer
  timer = setInterval(async () => {
    let nowTime = (await systemTime()).getTime()
    startSeconds = Math.round((startTime - nowTime) / 1000)
    endSeconds = Math.round((endTime - nowTime) / 1000)
    if (endSeconds <= 0) {
      clearInterval(timer)
    }
    if (callback) {
      callback(startSeconds, endSeconds)
    }
  }, 1000)
}

// 解析 授权后 cookie中的参数 uid，oid，img，name
export const parmsFormat = (parms) => {
  let reg = /^['"]+|['"]+$/g
  parms = parms.replace(reg, "") // 去除前后双引号
  let parmsArr = decodeURIComponent(parms).split("&&")
  let parmsObj = {}
  parmsArr.forEach(function (item) {
    let key = item.split("=")[0]
    let value = item.split("=")[1]
    parmsObj[key] = value
  })
  return parmsObj
}

/**
 * Description: 价格小数转换 value->转换值，decimal-> 保留几位小数
 * return: {
 * integerDecimal: 整数位 + 小数位
 * integer 整数位
 * decimal 小数位
 * }
 * /^(\+|-)?\d+($|\.\d+$)/ 是否数字
 */
export const decimalPice = (value = 0, decimal = 2) => {
  if (!/^(\+|-)?\d+($|\.\d+$)/.test(value)) value = 0
  value = value.toString()
  let index = value.indexOf(".")
  if (index !== -1) {
    value = value.substring(0, decimal + index + 1)
  } else {
    value = value.substring(0)
  }
  value = parseFloat(value).toFixed(decimal).split(".")
  return {
    integerDecimal: `${value[0]}.${value[1].substring(0, decimal)}`,
    integer: value[0],
    decimal: value[1].substring(0, decimal)
  }
}

// 大于指定数字时展示 指定数字+ 否则展示原数字
export const numberPlus = (value = 0, num = 999) => {
  if (!value && value != 0) value = 0
  let str = ""
  if (value > num) {
    str = num.toString() + "+"
  } else {
    str = value.toString()
  }
  return str
}

// 设置title
export const setTitle = (title) => {
  document.title = title
}

// 是否登陆 返回登陆cookie信息
export const loginStatus = () => {
  return getCookie("ul_utk") || getCookie("mall_cookie")
}

// 未登录进行跳转到登陆，登陆则跳转到目标页
export const navigateLogin = (url) => {
  let isLogin = loginStatus()
  if (isLogin) {
    window.location.href = decodeURIComponent(url)
  } else {
    window.location.href = `//m.${uleUrl()}/muser/user/login?target=${url}`
  }
}

// 自动登录跳转处理
export const checkLogin = (url) => {
  return new Promise((resolve, reject) => {
    let ua = navigator.userAgent.toLowerCase()
    let isWX = /micromessenger/.test(ua) && !/miniprogram/.test(ua)
    let isLogin = loginStatus()
    if (!isLogin) {
      if (isWX) {
        let selfLogin = localStorage.getItem("_utk_selflogin") || getCookie("self_login") || ""
        let selfLogout = getCookie("self_logout") || ""
        let wxid = getCookie("ul_wxid") || ""
        if (!wxid) {
          wxid = localStorage.getItem("_utk_wxid") || ""
          if (wxid) {
            let exp = new Date()
            exp.setTime(exp.getTime() + 1000 * 60 * 60 * 24 * 7)
            document.cookie = "ul_wxid=" + wxid + "; domain=" + uleUrl() + "; path=/; expires=" + exp.toGMTString()
          }
        }
        if (wxid && selfLogin == 1 && selfLogout != 1) {
          Jsonp(`//m.${uleUrl()}/muser/wx/user/syncWxAccount`, {}, "jsonCallback", "loginwx").then(
            (res) => {
              if (res.code == "0000") {
                resolve()
              } else {
                navigateLogin(url)
              }
            },
            () => {
              navigateLogin(url)
            }
          )
          return false
        }
      }
      navigateLogin(url)
    } else {
      resolve()
    }
  })
}

// 神策曝光
export const scExposure = (params) => {
  let uploadLog = []
  let isFirst = true
  const callBack = (entries, observer) => {
    // 第一次触发显示时会给所有的元素
    if (isFirst) {
      entries.forEach((item) => {
        let index = item.target.dataset.index
        uploadLog[index] = {
          isPush: false, // 是否上报过
          timer: -1 // 用于存储定时器编号
        }
      })
      isFirst = false
    }
    entries.forEach((item) => {
      let index = item.target.dataset.index
      // 先判断当前元素是否已经上报过日志
      if (uploadLog[index].isPush) {
        return false // 上报过直接 直接退出
      }
      if (item.isIntersecting) {
        // 开始计时, 5秒后添加神策数据
        uploadLog[index].timer = setTimeout((_) => {
          const scItem = JSON.parse(item.target.dataset.scitem)
          window.uleStatUtil &&
            window.uleStatUtil.sendSensorTrack("ylxd_ItemShow", {
              section_id: "", // 商品栏位名称
              exp_id: scItem.expId, // 实验id
              item_id: scItem.listingId, // 商品listingId
              is_recommendation: true, //
              module_sort: ~~index, // 商品排序
              ylxd_item_name: scItem.listName, // 商品名称
              ylxd_commodity_original_price: scItem.maxPrice, // 商品最高价格
              ylxd_commodity_current_price: scItem.minPrice, // 商品最低价格
              ylxd_current_page_type: params.name || "", // 当前页面名称
              ylxd_current_page_name: document.title, // 当前页面标题
              ylxd_page_area: params.moduleName || "" // 商品位置名称
            })
          // 上报完成后，状态修改为 true,避免重复上报
          uploadLog[index].isPush = true
        }, 5000)
      } else {
        // 如果元素移动出可视区域后，清除定时器
        if (uploadLog[index].timer) clearTimeout(uploadLog[index].timer)
      }
    })
  }
  const observer = new IntersectionObserver(callBack, { threshold: 0.99 })
  const liList = document.querySelectorAll(params.element)
  liList.forEach((item) => {
    observer.observe(item)
  })
}
export const checkFile = (fileValue, type) => {
  if (!fileValue) return false
  let index = fileValue.indexOf(".") //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
  let fileValueSuffix = fileValue.substring(index) //截断"."之前的，得到后缀
  if (type == "video") {
    if (!/(.*)\.(mp4|rmvb|avi|ts)$/.test(fileValueSuffix)) {
      //根据后缀，判断是否符合视频格式
      return false
    }
  }
  if (type == "image") {
    if (!/(.*)\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileValueSuffix)) {
      //根据后缀，判断是否符合图片格式
      return false
    }
  }
  return true
}
export const openNewWebView = (link, needTitle, title) => {
  window.dsBridge.call("generalAction", {
    type: "3",
    ios_action: `DetailWebViewController::1&&key::${link}`,
    android_action: `action&&ui.MyBusinessWebView##needJumpNewWeb::1**load_url::${link}**needTitle::${needTitle}**title::${title}`,
    logTitle: ""
  })
}
export const getHtmlImg = (html) => {
  const imgs = []
  html.replace(/]* src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
    console.log(match)
    console.log(capture)
    imgs.push(capture.replace(/^\/\/|http:\/\//, "https://"))
  })
  return imgs
}

// 获取当前cookie
export const getCookie = (name) => {
  var cookies = document.cookie.split(";")
  for (var i = 0, len = cookies.length; i < len; i++) {
    if (cookies[i].split("=")[0].trim() == name) {
      return cookies[i].split("=")[1]
    }
  }
}

export const tranNumber = (num, point) => {
  // 将数字转换为字符串,然后通过split方法用.分隔,取到第0个
  var numStr = num.toString().split(".")[0]
  if (numStr.length < 5) {
    // 判断数字有多长,如果小于6,,表示10万以内的数字,让其直接显示
    // console.log(numStr);
    return numStr
  } else if (numStr.length >= 5 && numStr.length <= 8) {
    // 如果数字大于6位,小于8位,让其数字后面加单位万
    var decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point)
    // console.log(decimal);
    // 由千位,百位组成的一个数字
    return parseFloat(parseInt(num / 10000) + "." + decimal) + "W"
  }
}

export function plusXing(str, star, frontLen, endLen) {
  str = str.toString()
  star = star != null ? star : 3
  frontLen = frontLen != null ? frontLen : 3
  endLen = endLen != null ? endLen : 3
  let xing = ""
  for (let i = 0; i < star; i += 1) {
    xing += "*"
  }
  return str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
}

//将对象装换为url拼接参数
export const changeSearch = (obj) => {
  let search = ""
  let i = 0
  for (let key in obj) {
    console.log("000", key, obj[key])
    if (i == 0) {
      search += "?"
    } else {
      search += "&"
    }
    search += key + "=" + obj[key]
    i++
  }
  return search
}

//动态加载js
export const loadScript = (url, callback) => {
  let scriptsArr = document.getElementsByTagName("script")
  let srcArr = []
  //获取所有的script地址
  for (var i = 0; i < scriptsArr.length; i++) {
    srcArr.push(scriptsArr[i].getAttribute("src"))
  }
  console.log("--0-0-0", srcArr)
  if (srcArr.indexOf(url) > -1) {
    //已加载的js不再重新加载
    return callback()
  }
  let script = document.createElement("script")
  script.type = "text/javascript"
  if (typeof callback != "undefined") {
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null
          callback()
        }
      }
    } else {
      script.onload = function () {
        callback()
      }
    }
  }
  script.src = url
  document.body.appendChild(script)
}

//app内设置原生title
export const setAppTitle = (title) => {
  if (browser().ule || browser().ylxd || browser().ylxdsq || browser().yzg) {
    loadScript("//i2.ulecdn.com/ulewap/j/cashierDesk/dsbridge.js", (res) => {
      dsBridge.call("setNativeTitle", { title: title })
    })
  } else {
    document.title = title
  }
}
//设app缓存
export const setLocalStorage = (key, value, phoneNumber) => {
  var curtime = new Date().getTime() // 获取当前时间 ，转换成JSON字符串序列
  var valueDate = JSON.stringify({
    val: value,
    timer: curtime,
    mobile: phoneNumber
  })
  dsBridge.call("setH5PageStatus", { page_key: key, page_value: valueDate })
}
//清除app缓存
export const delLocalStorage = (key) => {
  dsBridge.call("setH5PageStatus", { page_key: key, page_value: "" })
}
